import { use } from "react";
import "./index.css";
/**
 * use API 用于获取组件内部的Promise,或者Context的内容，
 * 该案例使用了use获取Promise返回的数据并且故意延迟2秒返回，模拟网络请求
 */
interface Data {
  name: string;
  age: number;
  address: string;
  avatar: string;
}

const getData = async () => {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  // 返回结果断言
  return (await fetch("http://localhost:5173/data.json").then((res) =>
    res.json()
  )) as { data: Data };
};

const dataPromise = getData();

export default function Card() {
  //   const [data, setData] = useState({});
  const { data } = use(dataPromise);

  return (
    <div className="card">
      <header className="card-header">
        <div className="card-name">{data.name}</div>
        <div className="card-age">{data.age}</div>
      </header>
      <section className="card-content">
        <div className="card-address">{data.address}</div>
        <div className="card-avatar">
          <img width={50} height={50} src={data.avatar} alt="" />
        </div>
      </section>
    </div>
  );
}
